package be.kuleuven.thesis.databases;

import be.kuleuven.thesis.framework.Album;
import be.kuleuven.thesis.framework.Song;

public class LastFmManager {
	private static final String API_KEY = "4f615dd522b7f59fc3c39093f820c136";
	//private static final String SECRET = "6edd2445777a3ff9404475ca557df590";
	private static final String ROOT = "http://ws.audioscrobbler.com/2.0/";
	
	private static LastFmManager instance = new LastFmManager();
	
	private LastFmManager() {
		
	}
	
	public static LastFmManager getInstance() {
		return instance;
	}
	
	public void fetchAlbumMetaData(Album album) {
		Song song = album.getSong();
		String method = "?method=track.getinfo&format=json&";
		String uri = method+"api_key="+API_KEY+"&artist="+makeStringForUri(song.getArtist())+"&track="+makeStringForUri(song.getTitle());
		String jString = HttpHelper.doGet(ROOT, uri);
		JSONParser.setMetaData(album, jString);
		if(album.getName().equals("Unknown")) {
			System.out.println(song.getTitle()+" heeft geen album");
			fetchArtistImages(album, song.getArtist());
		}
	}
	
	public void fetchArtistImages(Album album, String artist) {
		String method = "?method=artist.getinfo&format=json&";
		String uri = method+"api_key="+API_KEY+"&artist="+makeStringForUri(artist);
		String jString = HttpHelper.doGet(ROOT, uri);
		JSONParser.setImages(album, jString);
	}
	
	private String makeStringForUri(String input) {
		String[] words = input.split("\\s");
		if(words.length == 0)
			return "";
		String string = words[0];
		for(int i = 1; i < words.length; i++) {
			string = string + "+" + words[i];
		}
		return string;
	}
}
